package com.atos.optical.common;

import com.atos.optical.Enums.ResponseCodeEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author wanghra
 * @version 1.0
 * @description 统一响应信息
 * @date 2025/8/11
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ApiResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 响应数据
     */
    private T data;
    /**
     * 响应编号
     */
    private Integer code = ResponseCodeEnum.SUCCESS.getCode();
    /**
     * 响应信息
     */
    private String message = ResponseCodeEnum.SUCCESS.getMessage();

    public ApiResult(T data) {
        this.code = ResponseCodeEnum.SUCCESS.getCode();
        this.message = ResponseCodeEnum.SUCCESS.getMessage();
        this.data = data;
    }

    public ApiResult(ResponseCodeEnum responseCode) {
        this.data = null;
        this.code = responseCode.getCode();
        this.message = responseCode.getMessage();
    }

    public ApiResult(T data, ResponseCodeEnum responseCode) {
        this.data = data;
        this.code = responseCode.getCode();
        this.message = responseCode.getMessage();
    }

    public ApiResult(Throwable throwable) {
        this.message = throwable.getMessage();
        this.code = ResponseCodeEnum.FAIL.getCode();
    }

    public ApiResult(Throwable throwable, ResponseCodeEnum code) {
        this.message = throwable.getMessage();
        this.code = code.getCode();
    }

    public static ApiResult success(String message) {
        ApiResult result = new ApiResult();
        result.message = message == null ? "" : message;
        result.code = ResponseCodeEnum.SUCCESS.getCode();
        return result;
    }

    public static ApiResult failed(String message) {
        ApiResult result = new ApiResult();
        result.message = message;
        result.code = ResponseCodeEnum.FAIL.getCode();
        return result;
    }

    public static ApiResult failed(ServiceException e) {
        ApiResult result = new ApiResult();
        result.message = e.getMessage();
        if (e.getErrorCode() != null) {
            result.code = e.getErrorCode();
        } else {
            result.code = ResponseCodeEnum.FAIL.getCode();
        }
        return result;
    }
}
